import cv2
from wordcloud import WordCloud
from PIL import Image, ImageTk
import numpy as np
import jieba
import tkinter as tk
from io import BytesIO
import collections
import random

# 读取心形掩码图像并转换为合适格式
heart_mask_img = cv2.imread('d:\\img2.jpg')
heart_mask_img = cv2.cvtColor(heart_mask_img, cv2.COLOR_BGR2RGB)
heart_mask = np.array(heart_mask_img)

# 生成包含100个"浅笑安然"的文本并处理
words_list = [f"浅笑安然_{random.randint(1, 1000)}" for _ in range(100)]
words_str = " ".join(words_list)
words_cut = jieba.lcut(words_str)

# 统计词语频率（这里所有"浅笑安然"频率相同，但保留此步骤以保持结构完整）
word_count = collections.Counter(words_cut)

# 创建词云对象并生成词云
wc = WordCloud(mask=heart_mask, background_color="white", mode="RGB",
                font_path='C:\\Windows\\Fonts\\simhei.ttf', collocations=False)
wc.generate_from_frequencies(word_count)

# 将词云转换为字节流
image_bytes = BytesIO()
wc.to_image().save(image_bytes, format='PNG')
image_bytes.seek(0)

# 显示词云（如果不需要显示界面，可注释掉以下部分）
root = tk.Tk()
root.withdraw()

top = tk.Toplevel(root)
top.title("词云展示")

photo = ImageTk.PhotoImage(Image.open(image_bytes))
label = tk.Label(top, image=photo)
label.pack()

def on_close():
    top.destroy()
    root.quit()

top.protocol("WM_DELETE_WINDOW", on_close)

root.mainloop()